<template>
	<view class="container">
		<!-- 头部导航栏 -->
		<view class="header">
			<view class="header-left" @click="goBack">
				<uni-icons type="back" size="24" color="#333"></uni-icons>
			</view>
			<view class="header-title">收货地址</view>
			<view class="header-right" @click="addAddress">
				<text>添加</text>
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading">
			<uni-loading></uni-loading>
		</view>

		<!-- 地址选择区域 -->
		<view v-else class="address-selector">
			<view class="address-item" v-for="(address, index) in addressList" :key="index"
				@click="selectAddress(index)">
				<view class="address-checkbox">
					<uni-icons :type="selectedAddressIndex === index ? 'checkbox-filled' : 'circle'" size="24"
						:color="selectedAddressIndex === index ? '#e44d26' : '#ccc'"></uni-icons>
				</view>
				<view class="address-info">
					<view class="address-name-phone">
						<text class="name">{{ address.receiverName }}</text>
						<text class="phone">{{ address.receiverMobile }}</text>
					</view>
					<view class="address-detail">{{ address.location }} {{ address.detailedAddress }}</view>
				</view>
				<view class="address-actions">
					<view @click.stop="editAddress(address)">
						<uni-icons type="compose" size="20" color="#666" ></uni-icons>
					</view>
					<view @click.stop="deleteAddress(address.addressId)">
						<uni-icons type="trash" size="20" color="#ff3b30" ></uni-icons>
					</view>
				</view>
			</view>

			<!-- 无地址时的提示 -->
			<view v-if="total === 0" class="empty-tip">
				<text>暂无收货地址，请添加</text>
			</view>
		</view>

		<!-- 添加确认按钮 -->
		<view class="add-address-btn" @click="confirmSelection">
			<text>确认</text>
		</view>
	</view>
</template>
<script>
	export default {
		data() {
			return {
				addressList: [],
				selectedAddressIndex: -1, // 初始改为-1避免默认选中
				selectedAddressInfo: null,
				loading: true,
				userId: null,
				error: null,
				total: null,
			};
		},
		onShow() {
			// 每次页面显示时重新加载数据
			this.refreshData();
		},
		methods: {
			refreshData() {
				this.getUserProfile()
					.then(() => this.getAddressList())
					.then(() => {
						if (this.addressList.length > 0) {
							this.selectAddress(0);
						}
					})
					.catch((error) => {
						console.error('刷新数据出错:', error);
						this.showError('加载数据失败，请重试');
					});
			},
			// 选择地址方法
			selectAddress(index) {
				this.selectedAddressIndex = index;
				this.selectedAddressInfo = this.addressList[index];
			},

			// 确认选择
			confirmSelection() {
				if (!this.selectedAddressInfo) {
					uni.showToast({
						title: '请先选择收货地址',
						icon: 'none'
					});
					return;
				}

				// 通过事件通道发送数据
				const eventChannel = this.getOpenerEventChannel();
				eventChannel.emit('addressSelected', {
					addressId: this.selectedAddressInfo.addressId,
					receiverName: this.selectedAddressInfo.receiverName,
					receiverMobile: this.selectedAddressInfo.receiverMobile,
					location: this.selectedAddressInfo.location,
					detailedAddress: this.selectedAddressInfo.detailedAddress
				});

				uni.navigateBack();
			},

			// 返回按钮
			goBack() {
				uni.navigateBack();
			},

			// 获取用户信息
			async getUserProfile() {
				try {
					const res = await uni.request({
						url: 'http://localhost:8080/system/user/profile',
						method: 'GET',
						header: {
							'Content-Type': 'application/json',
							'Authorization': uni.getStorageSync('token')
						},
					});
					if (res.data.code === 200) {
						this.userId = res.data.data.userId;
					} else {
						throw new Error('获取用户信息失败，请重试');
					}
				} catch (error) {
					this.showError(error.message);
					throw error;
				}
			},

			// 获取地址列表
			async getAddressList() {
				this.loading = true;
				try {
					const url = `http://localhost:8080/address/address/list?userId=${this.userId}`;
					const res = await uni.request({
						url,
						method: 'GET',
						header: {
							'Content-Type': 'application/json',
							'Authorization': uni.getStorageSync('token')
						},
					});
					if (res.statusCode === 200 && res.data.code === 200) {
						this.addressList = res.data.rows;
						this.total = res.data.total;
					} else {
						throw new Error('获取地址失败，请重试');
					}
				} catch (error) {
					this.showError(error.message);
					throw error;
				} finally {
					this.loading = false;
				}
			},

			// 错误处理
			showError(message) {
				this.error = message;
				uni.showToast({
					title: message,
					icon: 'none'
				});
			},

			// 添加地址
			addAddress() {
				uni.navigateTo({
					url: '/pages/shop-address/shop-address-add',
				});
			},

			// 编辑地址
			editAddress(address) {
				uni.navigateTo({
					url: `/pages/shop-address/shop-address-edit?addressId=${address.addressId}`,
				});
			},

			// 删除地址
			async deleteAddress(addressId) {
				try {
					const token = uni.getStorageSync('token');
					const res = await uni.request({
						url: `http://localhost:8080/address/address/${addressId}`,
						method: 'DELETE',
						header: {
							'Content-Type': 'application/json',
							'Authorization': token
						}
					});
					if (res.statusCode === 200 && res.data.code === 200) {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						await this.refreshData();
						// 删除后重置选中状态
						if (this.addressList.length > 0) {
							this.selectAddress(0);
						} else {
							this.selectedAddressIndex = -1;
							this.selectedAddressInfo = null;
						}
					} else {
						throw new Error('删除失败');
					}
				} catch (error) {
					this.showError(error.message);
				}
			}
		}
	};
</script>
<style>
	.container {
		/* background-color: #f8f8f8; */
		background-color: #FFF8F0;
		color: #333;
		font-size: 14px;
	}

	/* 头部导航栏 */
	.header {
		/* 		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 15px;
		background-color: #fff;
		border-bottom: 1px solid #eee; */

		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 15px;
		background-color: #fff;
		border-bottom: 1px solid #eee;
		margin-bottom: 10px;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
	}

	.header-left,
	.header-right {
		display: flex;
		align-items: center;
	}

	.header-title {
		font-size: 16px;
		font-weight: bold;
	}

	/* 加载状态 */
	.loading {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200px;
	}

	/* 地址选择区域 */
	.address-selector {
		/* 	padding: 10px 15px;
		background: white; */
		height: 78vh;
		overflow-y: auto;
		padding: 2%;
		/* width: 94%; */
		margin: 0 auto;
		background: white;
		/* border-radius: 8px; */
		/* box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1); */
	}

	/* 滑动条样式区域 */
	/* 	.address-selector::-webkit-scrollbar {
		width: 4px;
	}

	.address-selector::-webkit-scrollbar-thumb {
		background: #e44d26;
		border-radius: 4px;
	} */

	.address-item {
		display: flex;
		align-items: center;
		padding: 10px 0;
		border-bottom: 1px solid #eee;
	}

	.address-checkbox {
		margin-right: 10px;
	}

	.address-info {
		flex: 1;
	}

	.address-name-phone {
		display: flex;
		justify-content: space-between;
		margin-bottom: 5px;
	}

	.name {
		font-size: 16px;
		font-weight: bold;
	}

	.phone {
		color: #666;
		margin-right: 10px;
	}

	.address-detail {
		color: #666;
	}

	.address-actions {
		display: flex;
		align-items: center;
		gap: 10px;
		z-index: 1000;
	}

	.add-address-btn {
		/* 		position: fixed;
		bottom: 20px;
		left: 20px;
		right: 20px;
		background-color: #e44d26;
		color: #fff;
		text-align: center;
		padding: 10px;
		border-radius: 5px;
		font-size: 16px; */
		
		background-color: #e44d26;
		color: #fff;
		text-align: center;
		padding: 10px;
		border-radius: 5px;
		font-size: 16px;
		width: 90%;
		margin: 10px auto 0;
	}

	/* 无地址时的提示 */
	.empty-tip {
		text-align: center;
		padding: 20px;
		color: #999;
	}
</style>
